/****************************************************************************
@FILENAME:	ble_packet_send.c
@FUNCTION:	pack ble opcode then send
@AUTHOR:	flege.zhang
@DATE:		2020.04.06
*****************************************************************************/

#include "ble_packet_send.h"
#include "ble_pack_opcode.h"
#include "ble_adv.h"

/******************************GLOBAL VARIABLE*******************************/
str_retention_memory 	ret_mem_data;
uint32_t 				GROUP_ADDR	= 0x0;
const uint8_t 			const_group_index[] 	= {0x00,0x01,0x02,0x03,0x04};


#if((BLE_ENCODER_VERSION&BLE_ENCODER_VIOT) == BLE_ENCODER_VIOT)
extern str_ble_viot_para 	ble_viot_para;
#endif


/**********************************FUNCTION**********************************/
inline void SET_GROUP_INDEX(uint8_t new_group_index)
{
	ret_mem_data.current_group_index = new_group_index;
}

inline uint8_t GET_GROUP_INDEX()
{
	return ret_mem_data.current_group_index;
}

void ble_packet_init()
{
	GROUP_ADDR = *(uint32_t*)(GROUP_ADDR_ROLL_CODE_BASE);
	
#if((BLE_ENCODER_VERSION&BLE_ENCODER_VIOT) == BLE_ENCODER_VIOT)
	memset(&ble_viot_para,0x0,sizeof(str_ble_viot_para));
#endif
}

uint8_t ble_packet_send()
{
	uint8_t 	ret = 0xFF;
	uint8_t 	encoded_data[31];
	uint8_t 	encoded_data_len;
	uint8_t 	index = 0x0;
	uint8_t* 	group_index = &ret_mem_data.current_group_index;
	uint16_t 	rand_seed = ret_mem_data.rand_seed;
	uint16_t 	tx_count = ret_mem_data.tx_count++;

	//validation check,if group index get error,reset as master group index
	*group_index = (*group_index > GROUP_INDEX_MAX) ? 0x00 : *group_index;
	
#if((BLE_ENCODER_VERSION&BLE_ENCODER_VIOT) == BLE_ENCODER_VIOT)
	ble_viot_para.type 			= 0x00;
	ble_viot_para.version 		= 0x00;
	ble_viot_para.count 		= tx_count;//count increace
	ble_viot_para.addr 			= GROUP_ADDR;
	ble_viot_para.group_index 	= *group_index;

	//encode packet
	ret = ble_viot_encoder(&ble_viot_para,rand_seed,encoded_data,&encoded_data_len);
#endif

	//send encoded packet
	ble_adv_send(index,encoded_data,encoded_data_len,SEND_BEACON_MAX_TIMES,SEND_BEACON_INTERVAL,SEND_BEACON_CHANNEL);

#if((BLE_ENCODER_VERSION&BLE_ENCODER_VIOT) == BLE_ENCODER_VIOT)
	memset(&ble_viot_para,0x0,sizeof(str_ble_viot_para));
#endif

	return ret;
}
